<template>
	<div>
		<div>
			<el-form :inline="true" ref="searchForm" :model="searchForm" class="forTbFilter flowStatistics"
				label-position="left" @submit.native.prevent>

				<el-form-item label="IMEI号：" v-if="curr_account_id == 2">
					<el-input v-model.trim="searchForm.imei" clearable></el-input>
				</el-form-item>

				<el-form-item label="所属客户：" v-if="curr_account_id == 2">
					<el-select v-model="searchForm.agentId" filterable placeholder="请选择或输入关键字" clearable
						@change="changeAgentId()">
						<el-option v-for="item in agentsOption" :value="item.id" :key="item.id"
							:label="item.name"></el-option>
					</el-select>
				</el-form-item>

				<el-form-item label="所属链接：" v-if="field_show.urlName=='1'">

					<!-- 根据选择的客户，选取所属链接 -->
					<el-select v-model="searchForm.urlId" filterable placeholder="请选择或输入关键字" clearable>
						<el-option v-for="item in urlsOption" :value="item.id" :key="item.id"
							:label="item.urlNote"></el-option>
					</el-select>
				</el-form-item>

				<el-form-item label="创建时间：" class="dateRange">
					<el-date-picker v-model="searchForm.time" range-separator="至" type="daterange"
						start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd"></el-date-picker>
				</el-form-item>


				<el-form-item class="btnArea">
					<el-button type="primary" @click="getFlowStatisticsHandler" icon="el-icon-search">查 询</el-button>
					<el-button type="primary" @click="excelSelect()" icon="el-icon-download">导出数据</el-button>
				</el-form-item>
			</el-form>
		</div>


		<el-table :data="tbpg.tableData" border height="600">
			<el-table-column type="index" label="序号"></el-table-column>
			<el-table-column prop="source" label="来源" v-if="curr_account_id != 2"></el-table-column>
			<el-table-column prop="urlName" label="链接名称" v-if="field_show.urlName=='1'"></el-table-column>
			<el-table-column prop="status" label="触发状态" v-if="curr_account_id != 2"></el-table-column>
			<el-table-column prop="agentName" label="客户名称" v-else-if="curr_account_id == 2"></el-table-column>
			<el-table-column prop="imei" label="imei" v-if="field_show.imei=='1'"></el-table-column>


			<!-- 新增，显示 phone字段 -->
			<!-- <el-table-column prop="phone" label="phone" v-if="field_show.userPhone=='1'"></el-table-column> -->
			<!-- 新增，显示 phone字段 -->

			<!-- <el-table-column prop="place" label="归属地"></el-table-column> -->

			<el-table-column prop="idfa" label="idfa" v-if="field_show.imei=='1'"></el-table-column>
			<el-table-column prop="oaid" label="oaid" v-if="field_show.oaid=='1'"></el-table-column>
			<el-table-column prop="oaid_md5" label="oaid_md5" v-if="field_show.oaid_md5=='1'"></el-table-column>
			<el-table-column prop="campaign_name" label="广告计划"
				v-if="field_show.campaign_name=='1'"></el-table-column>
			<el-table-column prop="createTime" label="创建时间" v-if="field_show.createTime=='1'"></el-table-column>
		</el-table>
		
		
		
		<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
			:current-page="tbpg.currentPage" :page-sizes="[15, 50, 100, 500]" :page-size="tbpg.pageSize"
			layout="total, sizes, prev, pager, next, jumper" :total="tbpg.total">
		</el-pagination>

	</div>
</template>
<script>
	import {
		flowStatistics,
		flowEveryDayDetail,
		flowEveryMonthDetail,
		flowStatisticsExport
	} from '@/api/csm.js'

	// 原始的获取抖音消息的链接
	// import {getDouyingInfo} from '@/api/fluxPools.js'

	import {
		getDouYinPermissionInfo
	} from '@/api/fluxPools.js'

	import {
		getFieldList
	} from '@/api/fieldManage.js'

	import common from '@/utils/common.js'
	// var echarts = require('echarts'); // 引入 ECharts 主模块
	export default {
		data() {
			return {

				// 不同角色 允许显示的字段
				field_show: {
					"imei": "1",
					"userPhone": "1",
					"idfa": "1",
					"oaid": "1",
					"oaid_md5": "1",
					"campaign_name": "1",
					"createTime": "1",
					"urlName": "1"
				},
				
				curr_account_id: "",
				
				batchOptVisible1: false,
				batchOptForm1: {
					countMonth: ''
				},
				agentsOption: [],
				urlsOption: [],
				searchForm: {
					agentId: '',
					urlId: '',
					imei: ''
				},
				pkgGroup: [],
				//每月流量详情表
				tbpg: {
					tableData: [],
					currentPage: 1,
					pageSize: 15,
					total: 0
				},

				//每日流量详情表
				everyDayTbpg: {
					tableData: [],
					currentPage: 1,
					pageSize: 15,
					total: 0
				},
				thisMonth: '',
				activeName: 'everyMonthTable',
				everyDayAmountData: [],
				branchSupplierOption: [],
				monthFlow: [{
					createTime: '',
					dataAmount: ''
				}],

				stopMessage: '0',
				moreThanNumber: '0',
				sumTotoalData: '0',
				totalOutData: '0'

			}
		},
		methods: {

			// 当改变了客户列表选择时
			changeAgentId() {
				this.handleTiktosPermissionUrlList();
			},

			sureBatchChgStateHandler1() {
				this.$refs.batchOptForm1.validate(valid => {
					if (valid) {
						this.$refs.upload.submit();
					}
				});
			},
			handleSuccess(res) {
				if (res.code == 200) {
					this.$message.success(res.message);
				} else {
					this.$message.error(res.message);
				}
				this.cancel();
				this.$refs.upload.clearFiles();
			},


			downPdf() {
				var link = document.createElement('a');
				link.setAttribute('download', '');
				link.href = '../../../doc/查询模板.xls';
				link.click();
			},
			cancel() {
				this.batchOptVisible1 = false;
				this.$refs.batchOptForm1.resetFields();
			},
			excelSelect($event) {
				common.resetCurrentPage(this, $event, 'tbpg');
				var data = common.getRequestParams(this, 'tbpg', this.searchForm);
				data.token = localStorage.getItem('token');
				common.sysRequest('excels/all/urlInfos', data, 'post').then(res => {
					if (res.data.code == 200) {
						this.$message.success('下载中，请稍后在下载管理中查询');
					} else {
						this.$message.error(res.data.message);
					}
				})
			},


			// 触发查询按钮
			getFlowStatisticsHandler($event) {
				common.resetCurrentPage(this, $event, 'tbpg');
				var data = common.getRequestParams(this, 'tbpg', this.searchForm);

				// 原始获得抖音数据的连接
				//  getDouyingInfo(data).then(res => {
				//     common.listCallback(this, res, 'tbpg');
				// })



				// wzyk新增，如果是非超级用户，需要新增字段 source，和 修改字段 连接名称
				getDouYinPermissionInfo(data).then(res => {
					let that = this;
					// console.log(res.data.data);
					if (res.data.data == null){
						that.tbpg.tableData = [];
						// common.listCallback(this, res, 'tbpg');
						return;
					}
					if (that.curr_account_id != 2){
						var source = ["抖音", "头条"];
						var status_type = ["视频展示", "有效触点", "视频播放", "视频播完", "视频有效播放"];
						// console.log(res.data.data.resultList);
						var tem = res.data.data.resultList;
						for (var i = 0; i < tem.length; i++){
							// console.log(tem[i].urlName);
							let firstChar = tem[i].urlName.charAt(0);
							let lastChar = tem[i].urlName.charAt(tem[i].urlName.length-1);
							// console.log(firstChar);
							// console.log(lastChar);
							// console.log(typeof(tem[i]));
							if(firstChar==1){
								tem[i]["source"] = "抖音";
							}
							tem[i]["status"] = status_type[parseInt(lastChar)-1];
						}
						
					}
					common.listCallback(this, res, 'tbpg')
				})
				// wzyk新增
			},

			// formatDataAmount(){
			//     this.searchForm.dataAmount = this.searchForm.dataAmount.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1');
			// },

			//获取每日流量数据
			getFlowEveryDayHandler($event) {
				common.resetCurrentPage(this, $event, 'tbpg');
				var data = common.getRequestParams(this, 'tbpg', this.searchForm);
				if (data.dataAmount) {
					data.dataAmount = data.dataAmount * 1024;
				}
				data.iccid = this.currentIccic;
				flowEveryDayDetail(data).then(res => {
					common.listCallback(this, res, 'everyDayTbpg');
					this.activeName = 'everyDayTable';
				})
			},

			goToDetailPage(row) {
				this.$store.commit('menu/setFromPage', 'orderMgt');
				this.$store.commit('menu/setFromPageIccid', row.iccid);
				document.getElementById('cardDetailsMenu').click();
			},

			exportInfoHandle() { //导出excel文件
				this.$confirm("确定要导出吗？", "提示", {
					confirmButtonText: '确定',
					cancelButtonText: '取消'
				}).then(() => {
					let param = this.searchForm;
					flowStatisticsExport(param).then(res => {
						if (res.data.code == 200) {
							this.$message.success('数据导出中,请稍候去任务中心下载');
						} else {
							this.$message.error(res.data.msg);
						}
					}).catch(err => console.error(err));
				}).catch(() => {});
			},


			drawFlowStatisticsChart(elementId, everyDayAmountData) {
				let dataAxis = [];
				let data = [];
				let yMax = 500;
				let dataShadow = [];
				let myChart = echarts.init(document.getElementById(elementId));



				for (let i = 0; i < everyDayAmountData.length; i++) {
					dataAxis.push(everyDayAmountData[i].createTime);
					data.push(everyDayAmountData[i].dataAmount);
				}

				yMax = Math.max(...data);

				for (let i = 0; i < data.length; i++) {
					dataShadow.push(yMax);
				}


				let option = {
					title: {
						text: '每日流量统计',
					},
					xAxis: {
						data: dataAxis,
						axisTick: {
							show: false
						},
						axisLine: {
							show: false
						},
						z: 10
					},
					yAxis: {
						axisLine: {
							show: false
						},
						axisTick: {
							show: false
						},
						axisLabel: {
							textStyle: {
								color: '#999'
							}
						}
					},
					dataZoom: [{
						type: 'inside'
					}],
					series: [{ // For shadow
							type: 'bar',
							itemStyle: {
								normal: {
									color: 'rgba(0,0,0,0.05)'
								}
							},
							barGap: '-100%',
							barCategoryGap: '40%',
							data: dataShadow,
							animation: false,
						},
						{
							type: 'bar',
							label: {
								normal: {
									show: true,
									position: 'insideTop'
								}
							},
							itemStyle: {
								normal: {
									color: new echarts.graphic.LinearGradient(
										0, 0, 0, 1,
										[{
												offset: 0,
												color: '#83bff6'
											},
											{
												offset: 0.5,
												color: '#188df0'
											},
											{
												offset: 1,
												color: '#188df0'
											}
										]
									)
								},
								emphasis: {
									color: new echarts.graphic.LinearGradient(
										0, 0, 0, 1,
										[{
												offset: 0,
												color: '#2378f7'
											},
											{
												offset: 0.7,
												color: '#2378f7'
											},
											{
												offset: 1,
												color: '#83bff6'
											}
										]
									)
								}
							},
							data: data
						}
					]
				};

				myChart.setOption(option);
			},

			handleSizeChange(val) {
				this.tbpg.pageSize = val;
				this.getFlowStatisticsHandler();
			},
			handleCurrentChange(val) {
				this.tbpg.currentPage = val
				this.getFlowStatisticsHandler();
			},

			// 获取客户自己的链接
			handleTiktosPermissionUrlList() {
				// //wzyk 新增
				common.sysRequest('tiktok/permissionList/all', this.searchForm, 'post').then(res => {
					if (res.data.code == 200) {
						this.urlsOption = res.data.data;
					}
				})
			},

			// 给不同用户装配可显示字段
			handleFieldShow() {
				let that = this;
				getFieldList().then(res => {
					if (res.data.message === "2") {
						that.field_show.campaign_name = "1";
						that.field_show.create_time = "1";
						that.field_show.idfa = "1";
						that.field_show.imei = "1";
						that.field_show.oaid = "1";
						that.field_show.oaid_md5 = "1";
						that.field_show.phone = "1";
						that.field_show.urlName = "1";
					} else {
						var list = res.data.data;
						for (var i = 0; i < list.length; i++) {
							if (list[i]["source"] != "抖音") {
								continue;
							}
							if (list[i]["name"] === "imei" && list[i]["status"] === "0") that.field_show.imei =
							"0";
							if (list[i]["name"] === "idfa" && list[i]["status"] === "0") that.field_show.idfa =
							"0";
							if (list[i]["name"] === "oaid" && list[i]["status"] === "0") that.field_show.oaid =
							"0";
							if (list[i]["name"] === "oaid_md5" && list[i]["status"] === "0") that.field_show
								.oaid_md5 = "0";
							if (list[i]["name"] === "campaign_name" && list[i]["status"] === "0") that.field_show
								.campaign_name = "0";
							if (list[i]["name"] === "createTime" && list[i]["status"] === "0") that.field_show
								.createTime = "0";
							if (list[i]["name"] === "userPhone" && list[i]["status"] === "0") that.field_show
								.userPhone = "0";
							if (list[i]["name"] === "urlName" && list[i]["status"] === "0") that.field_show
								.urlName = "0";
						}
					}
				})
			}

		},
		created() {
			this.curr_account_id = localStorage.getItem("id")
		},

		mounted() {
			this.getFlowStatisticsHandler();
			// 装填 agentid 列表
			common.getNextAgentOptsCom(this, 'agentsOption');
			// 原始获取专属链接操作


			// common.sysRequest('tiktok/list/all', this.searchForm, 'post').then(res => {
			//      if(res.data.code == 200){
			//         this.urlsOption=res.data.data;
			//      }
			//  })


			// // //wzyk 新增
			// common.sysRequest('tiktok/permissionList/all', this.searchForm, 'post').then(res => {
			// 	if (res.data.code == 200) {
			// 		this.urlsOption = res.data.data;
			// 	}
			// })

			this.handleTiktosPermissionUrlList();
			this.handleFieldShow();
		},

		updated: function() {

		},
		computed:{
			
		},

		watch: {

		}
	}
</script>

<style>
	.flowStatistics .el-input-group__prepend,
	.flowStatistics .el-input-group__append {
		background-color: #f5f5f5;
	}

	.flowStatistics .el-form-item__content {
		width: 250px;
	}
</style>

<style lang="less" scoped>
	.forTbFilter {
		display: inline-block;

		.btnArea {
			display: inline-block;
			margin-left: 30px;

		}
	}

	.stopMessage {
		font-size: 18px;
		margin: 0 0 10px 0;

		span {
			color: #ea2929;
			margin-right: 60px;

		}
	}
</style>